﻿using System;
using System.Net;
using ETModel;
using ETHotfix;

namespace DemoPathfinding.Hotfix.Handlers {
    [MessageHandler(AppType.Realm)]
    public class C2R_LoginHandler : AMRpcHandler<C2R_Login, R2C_Login> {
        protected override void Run(Session session, C2R_Login message, Action<R2C_Login> reply) {
            RunAsync(session, message, reply).Coroutine();
        }

        private async ETVoid RunAsync(Session session, C2R_Login message, Action<R2C_Login> reply) {
            R2C_Login response = new R2C_Login();
            try {
                if (string.IsNullOrEmpty(message.UserAccount) || string.IsNullOrEmpty(message.Password)) {
                    response.Error = ErrorCode.ERR_AccountOrPasswordError;
                    response.Message = "请输入帐号和密码!";
                    reply(response);
                    return;
                }

                //这里就不做帐号密码的验证了


                // 分配一个Gate
                StartConfig config = Game.Scene.GetComponent<RealmGateAddressComponent>().GetAddress();
                IPEndPoint innerAddress = config.GetComponent<InnerConfig>().IPEndPoint;
                Session gateSession = Game.Scene.GetComponent<NetInnerComponent>().Get(innerAddress);

                // 向gate请求一个GateLoginKey,客户端可以拿着这个GateLoginKey连接gate(即:Gate服务器不做帐号认证的事情)
                G2R_GetLoginKey g2RGetLoginKey = (G2R_GetLoginKey)await gateSession.Call(new R2G_GetLoginKey() { UserAccount = message.UserAccount });

                string outerAddress = config.GetComponent<OuterConfig>().Address2;

                response.GateAddress = outerAddress;
                response.GateLoginKey = g2RGetLoginKey.GateLoginKey;
                reply(response);
            } catch (Exception e) {
                ReplyError(response, e, reply);
            }
        }
    }
}